import Taro, { Component } from '@tarojs/taro'
import { View, Text, Checkbox, Icon } from '@tarojs/components'
import './index.scss'

import GoodList from '../../components/orderSubmit/goodList'
import Posmethod from '../../components/orderSubmit/posmethod'
import Deduction from '../../components/orderSubmit/deduction'
import GoodPrice from '../../components/orderSubmit/goodPrice'
import Footer from '../../components/orderSubmit/footer'
import PopGoodList from '../../components/orderSubmit/popGoodList'
import PopCoupon from '../../components/orderSubmit/popCoupon'
import PreView from '../../components/weui/preview'

import { set as setGlobalData, get as getGlobalData } from '../../static/js/global_data'
import api from '../../service/api'
import common from '../../service/common'
import base from '../../static/js/base'

export default class Index extends Component {
    config = {
        navigationBarTitleText: '结算'
    }
    constructor() {
        super(...arguments)
        this.state = {
            domainImg: getGlobalData("domainImg"),
            shopInfo: getGlobalData('shopInfo'),
            popGoodList: false,
            popCoupon: false,
            yhqid: '', //领取的优惠券
            psmethod: '', //配送方式
            isactive: 1, //是否要参加促销活动(1参加，2不参加)
            intergralState: 1, //0不开启，1开启
            balanceState: 1,//0不开启，1开启
            isShopping: 0, //是否开启购物卡支付 0未开启,1开启
            MarketingPrice: null, //优惠券优惠金额

            cart: [],
            totalNum: 0,
            posmethod: [], // 配送方式
            userInfo: null,
            hasView: false,
            goodType: '',
        }
    }

    componentWillMount() {
        base.showLoading('加载中...')
        console.log('orderSubmitMarketing.params--------------------')
        console.log(this.$router.params)
        const that = this;
        const goodType = this.$router.params.goodType || ''
        const totalNum = this.$router.params.totalNum
        let pintuanGslistdt = this.$router.params.pintuanGslistdt || null
        pintuanGslistdt = JSON.parse(pintuanGslistdt)
        const postime = this.state.shopInfo.model.c_deliver
        this.state.totalNum = totalNum
        const prevData = base.prevPage().state
        if(goodType == ''){ // 普通商品
            console.log('普通')
            common.getUserInfo(this, (res) => {
                this.setState({
                    userInfo: res
                })
            })
            this.setState({
                totalNum: this.$router.params.totalNum || 0,
                cids: this.$router.params.cids || null,
            }, () => {
                common.getOrderDetail(this,this.state.cids, () => {
                    common.getOrderPrices(this,() => {
                        this.setState({
                            hasView: true
                        })
                        Taro.hideLoading()
                    })
                })
            })
        }else if (goodType == 'exchange') { // 积分兑换
            console.log('积分')
            let orderIntegral = prevData.giftGoods.N_IG_INTEGRAL * totalNum
            prevData.giftGoods.N_NUM = totalNum
            this.state.cart.push(prevData.giftGoods)
            this.setState({
                orderIntegral: orderIntegral,
            })
            that.getPromiseAll()
        } else if (goodType == 'pintuan') { // 拼团
            console.log('拼团')
            prevData.goodsInfo.N_GSPrice = prevData.pinTuanData.N_GSPrice
            prevData.goodsInfo.N_NUM = totalNum
            this.state.cart.push(prevData.goodsInfo)
            that.getPromiseAll()
        }
        this.setState({
            goodType: goodType,
            postime: postime,
            totalNum: this.state.totalNum,
            cart: this.state.cart,
            pinTuanData: prevData.pinTuanData ? prevData.pinTuanData : null,
            pintuanGslistdt: pintuanGslistdt,
        })
        
    }

    componentDidShow() {
        let {goodType} = this.state
        if(this.state.refresh){
            if(goodType == ''){
                base.showLoading('加载中...')
                common.getOrderPrices(that,() => {
                    Taro.hideLoading()
                    that.setState({
                        refresh: false,
                    })
                })
            }else{
                let postmoney = 0;
                this.state.posmethod.map((item,i) => {
                    if(item.n_isdefault == 1){
                        postmoney = item.n_freight
                    }
                })
                this.setState({
                    postmoney: postmoney,
                    posmethod: this.state.posmethod,
                    refresh: false,
                })
            }
        }
    }
    // 达达配送下预订单 1802
    knightDelivery(that, callback) {
        getQhdate(that)
        if (that.data.prices.ordermoney == 0) {
            that.data.prices.ordermoney = "0"
        }
        const address = that.data.address
        const str = `cmbname&cmbphone&caddress&clng&clat&cargoprice&qhdate&ShopNo`
        const params = {
            bNo: 1802,
            cmbname: address.C_MB_NAME,
            cmbphone: address.C_MB_PHONE,
            caddress: address.C_PROVINCE + address.C_CITY + address.C_COUNTY + address.C_ADDRESS,
            clng: address.C_MB_LONGITUDE[0],
            clat: address.C_MB_LONGITUDE[1],
            cargoprice: that.data.prices.ordermoney,
            qhdate: that.data.qhdate,
        }
        app.remote(str, params, function (res) {
            console.log("骑士专送")
            console.log(res)
            that.setData({
                qspostmoney: res.fee,
                psno: res.dadaptid
            })
            callback()
        })
    }
    // 拼团、积分兑换请求
    getPromiseAll() {
        // 获取用户信息
        let getUserInfo = new Promise((resolve, reject) => {
            common.getUserInfo(this, (res) => {
                resolve(res)
            })
        })
        let getSendmethod = new Promise((resolve, reject) => {
            this.getSendmethod((res) => {
                resolve(res)
            })
        })
        let getAddress = new Promise((resolve, reject) => {
            this.getAddress((res) => {
                resolve(res)
            })
        })
        let getSelflift = new Promise((resolve, reject) => {
            this.getSelflift((res) => {
                resolve(res)
            })
        })
        Promise.all([getUserInfo, getSendmethod, getAddress, getSelflift]).then((res) => {
            console.log(res);
            let postmoney = 0;
            let orderprice = 0; // 订单合计+运费
            let orderyprice = 0; // 商品金额
            res[1].sendmethod.map((item,i) => {
                if(item.n_isdefault == 1){
                    postmoney = item.n_freight
                    this.state.psmethod = item.c_psname
                }
            })
            if(this.state.psmethod == ''){
                res[1].sendmethod[0].n_isdefault = 1
                this.state.psmethod =  res[1].sendmethod[0].c_psname
            }
            if(this.state.goodType == 'pintuan'){
                orderyprice = parseFloat(this.state.cart[0].N_GSPrice * this.state.cart[0].N_NUM).toFixed(2)
                orderprice = parseFloat(this.state.cart[0].N_GSPrice * this.state.cart[0].N_NUM) + postmoney
            }
            this.setState({
                userInfo: res[0],
                posmethod: res[1].sendmethod,
                address: res[2].address,
                selflift: res[3].StoreSince,
                postmoney: postmoney,
                psmethod: this.state.psmethod,
                orderprice: orderprice,
                orderyprice: orderyprice,
                hasView: true
            })
            console.log(res[1].sendmethod)
            Taro.hideLoading()
        });
    }
    // 获取配送列表
    getSendmethod(callback) {
        const str = `ShopNo`
        const params = {
            bNo: 900
        };
        api.get(str, params, (res) => {
            if(!res.sendmethod){res.sendmethod = []}
            if (callback) { callback(res) }
        })
    }
    // 获取地址
    getAddress(callback) {
        const userInfo = Taro.getStorageSync('userInfo')
        const str = `mebno&ShopNo`
        const params = {
            bNo: 1003,
            mebno: userInfo.C_MB_NO,
        };
        api.get(str, params, (res) => {
            if (callback) { callback(res) }
        })
    }
    // 获取自提列表
    getSelflift(callback) {
        const str = `ShopNo`
        const params = {
            bNo: 903,
        };
        api.get(str, params, (res) => {
            if (!res.StoreSince) { res.StoreSince = [] }
            res.StoreSince[0].def = 1
            if (callback) { callback(res) }
        })
    }
    // 显示结算商品列表弹窗
    popGoodListState() {
        if (this.state.cart && this.state.cart.length > 0) {
            this.setState({ popGoodList: !this.state.popGoodList })
        }
    }
    // 点击优惠券展示优惠券列表层
    couponTap() {
        if (this.state.marketimg && this.state.marketimg.length > 0) {
            this.setState({ popCoupon: !this.state.popCoupon })
        }
    }
    // 选择优惠券
    selectCheck(sec, index) {
        if (sec == 'coupon') { //优惠券
            this.state.marketimg.map((item, i) => {
                item.select = index == i ? true : false
            })
            this.setState({
                marketimg: this.state.marketimg,
                yhqid: this.state.marketimg[index].MarketingCId,
                MarketingPrice: this.state.marketimg[index].MarketingPrice
            }, () => {
                common.getOrderPrices(this)
            })
        }
    }
    // 积分、余额切换
    switchTap(types) {
        if (types == 'intergral') { //积分
            const intergralState = this.state.intergralState == 1 ? 0 : 1
            this.setState({ intergralState: intergralState }, () => {
                if(this.state.goodType == ''){
                    common.getOrderPrices(this)
                }
            })
        } else if (types == 'balance') { //余额
            const balanceState = this.state.balanceState == 1 ? 0 : 1
            this.setState({ balanceState: balanceState }, () => {
                if(this.state.goodType == ''){
                    common.getOrderPrices(this)
                }
            })
        }
    }
    // 备注
    onInput(id, e) {
        if (id == 'remark') { // 备注
            this.setState({ remark: e.detail.value })
        }
    }
    // 新增订单
    addOrder(callback) {
        if (this.state.psmethod != '上门自提') {
            if (!this.state.address) {
                base.showToast('请先选择地址！', 'none')
                return
            }
        }
        const address = this.state.address;
        const _address = address ? address.C_PROVINCE + address.C_CITY + address.C_COUNTY + address.C_ADDRESS : ''
        const userInfo = Taro.getStorageSync('userInfo')
        const str = `mebno&yhqstr&name&phone&address&cids&ShopNo`
        let params = {
            bNo: 401,
            mebno: userInfo.C_MB_NO,
            yhqstr: this.state.yhqid,
            name: address ? address.C_MB_NAME : '',
            phone: address ? address.C_MB_PHONE : '',
            address: _address,
            cids: this.state.cids,
            psmethod: this.state.psmethod,
            isactive: this.state.isactive, //是否要参加促销活动(1参加，2不参加)
            isIntergral: this.state.intergralState,
            isBalance: this.state.balanceState,
            isShopping: this.state.isShopping || 0,
            remark: this.state.remark || '',
            saleids: this.state.saleids || '',
            zpid: this.state.zpid || '',
            shoppingcardid: this.state.shoppingcardid || '',
        }
        if (this.state.psmethod == '上门自提') {
            if (this.state.selfliftSelect) {
                params.THShopName = this.state.selfliftSelect.c_thname
                params.THPhone = this.state.selfliftSelect.c_lxphone
                params.THAddress = this.state.selfliftSelect.priname + this.state.selfliftSelect.cityname + this.state.selfliftSelect.areaname + this.state.selfliftSelect.c_adress
                params.THName = this.state.selfliftSelect.c_lxname
                params.longitude = this.state.selfliftSelect.c_jd
                params.dimension = this.state.selfliftSelect.n_wd
            }
        }
        api.get(str, params, (res) => {
            if (res.payamount == '0') {
                Taro.navigateTo({ url: `/pages/payResult/payResult?result=0&&orderno=${res.orderNo}` })
            } else {
                if (callback) {
                    callback(res)
                }
            }
        })
    }
    // 积分兑换-确定是否在配送范围
    isDelivery(callback){
        let n_pslx = null,addid = this.state.address.N_MA_ID;
        this.state.posmethod.map((item,i) => {
            if(item.c_psname == this.state.psmethod){
                n_pslx = item.n_ps_lx
            }
        })
        const str = `n_pslx&addid&ShopNo`
        let params = {
            bNo: 904,
            n_pslx: n_pslx,
            addid: addid,
        }
        api.get(str, params, (res) => {
            if (callback) { callback(res) }
        })
    }
    // 新增订单 -- 积分兑换、拼团
    addOrderMarketing(callback){
        const name = this.state.address ? this.state.address.C_MB_NAME : ''
        const phone = this.state.address ? this.state.address.C_MB_PHONE : ''
        const address = this.state.address ? this.state.address.C_PROVINCE + this.state.address.C_CITY + this.state.address.C_COUNTY + this.state.address.C_ADDRESS : ''
        let str = ``
        let params = {}
        if(this.state.goodType == 'exchange'){ // 积分兑换
            str = `mebno&gid&Num&name&phone&address&psmethod&ShopNo`
            params = {
                bNo: 430,
                mebno: this.state.userInfo.C_MB_NO,
                gid: this.state.cart[0].N_GOODSID,
                Num: this.state.cart[0].N_NUM,
                psmethod: this.state.psmethod,
                posmoney: this.state.postmoney,
                name,
                phone,
                address,
            }
        }
        else if(this.state.goodType == 'pintuan'){
            str = `mebno&gsid&gid&name&phone&address&ShopNo`
            params = {
                bNo: 612,
                groupno: this.state.pintuanGslistdt ? this.state.pintuanGslistdt.C_GroupNo : '',
                gid: this.state.pinTuanData.N_SKU_ID,
                mebno: this.state.userInfo.C_MB_NO,
                yhqstr: '',
                saleids: '',
                name,
                phone,
                address,
                cids: "",
                Num: this.state.totalNum,
                qspostmoney: 0,
                isIntergral: this.state.intergralState,
                isBalance: this.state.balanceState,
                isShopping: 0,
                shoppingcardid: 0,
                remark: this.state.remark || '',
                isgroupshop: 1,
                gsid: this.state.pintuanGslistdt ? this.state.pintuanGslistdt.N_GS_Id : this.state.pinTuanData.N_Id,
            };
        }
        if(this.state.psmethod == '上门自提'){
            let selectSelflift = {}
            this.state.selflift.map((item,i) => {
                if(item.def == 1){
                    selectSelflift = item
                }
            })
            params.THShopName = selectSelflift.c_thname; // 店铺名
            params.THPhone = selectSelflift.c_lxphone; // 店铺电话
            params.THAddress = selectSelflift.c_adress; // 店铺地址
            params.THName = selectSelflift.c_lxname; // 店主名
        }
        api.get(str, params, (res) => {
            console.log(res)
            if(res.code == '101'){
                base.showModal(res.msg)
                Taro.hideLoading()
            }else{
                if (res.payamount == '0') {
                    Taro.hideLoading()
                    Taro.navigateTo({ url: `/pages/payResult/payResult?result=0&&orderno=${res.orderNo}` })
                } else {
                    if (callback) {
                        callback(res)
                    }
                }
            }
        },(err) => {
            console.log(err)
            base.showModal(err.msg)
            Taro.hideLoading()
        })
    }
    // 提交订单
    footBtn(types) {
        Taro.showLoading({
            title: '加载中...',
            mask: true
        })
        if(this.state.goodType == ''){
            this.addOrder((data) => {
                common.payment(data.orderNo)
            })
        }
        else if (this.state.goodType == 'exchange') { // 积分兑换
            if(this.state.psmethod == '上门自提'){
                this.isDelivery(() => {
                    this.addOrderMarketing((data) => {
                        common.payment(data.orderNo)
                    })
                })
            }else{
                this.addOrderMarketing((data) => {
                    common.payment(data.orderNo)
                })
            }
        }else if(this.state.goodType == 'pintuan'){ // 拼团
            this.addOrderMarketing((data) => {
                common.payment(data.orderNo)
            })
        }
        
    }

    render() {
        let { goodType, cart, totalNum, popGoodList, posmethod, userInfo, orderIntegral,postmoney, hasView } = this.state
        return (
            <View className='mainOrderDetail'>
                {hasView &&
                    <Block>
                        <View className='weui-cells weui-cells-none m0'>
                            {/*  商品列表*/}
                            <View className='goodList weui-cell'>
                                <View className='weui-cell__bd'>
                                    <GoodList goodlist={cart} totalNum={totalNum} onShowPopGoodList={this.popGoodListState.bind(this)}></GoodList>
                                </View>
                            </View>
                            {/* 商品列表弹窗 */}
                            <View className='popGoodList'>
                                <PopGoodList popGoodList={popGoodList} goodList={cart} goodType={goodType} onHidePopGoodList={this.popGoodListState.bind(this)}></PopGoodList>
                            </View>
                            {/* 配送方式 */}
                            <View className='posmethod weui-cell'>
                                <View className='weui-cell__bd'>
                                    <Posmethod posmethod={posmethod} postime={this.state.postime} selflift={this.state.selflift}></Posmethod>
                                </View>
                            </View>
                        </View>
                        {/* 拼团、活动商品、普通商品 pintuan、'' */}
                        {goodType != 'exchange' &&
                            <Block>
                                <View className='weui-cells weui-cells-none'>
                                    {/*  优惠券、购物卡、积分、余额、等*/}
                                    <View className='goodList weui-cell weui-cell-p0'>
                                        <View className='weui-cell__bd'>
                                            <Deduction
                                                goodType={goodType}
                                                marketimg={this.state.marketimg} yhqid={this.state.yhqid} onCouponTap={this.couponTap.bind(this)}
                                                intergralState={this.state.intergralState} Intergral={this.state.Intergral} IntergralMoney={this.state.IntergralMoney}
                                                balanceState={this.state.balanceState} onSwitchTap={this.switchTap.bind(this)}
                                                userInfo={this.state.userInfo}
                                            ></Deduction>
                                        </View>
                                    </View>
                                    {/* 优惠券选择弹窗 */}
                                    {this.state.marketimg && this.state.marketimg.length > 0 &&
                                        <View className='pop-coupon'>
                                            <PopCoupon popCoupon={this.state.popCoupon} marketimg={this.state.marketimg} onSelectCheck={this.selectCheck.bind(this, 'coupon')} onHidePopCoupon={this.couponTap.bind(this)}></PopCoupon>
                                        </View>
                                    }
                                </View>
                                <View className='weui-cells weui-cells-none'>
                                    {/*  商品金额 */}
                                    <View className='goodList weui-cell weui-cell-p0'>
                                        <View className='weui-cell__bd'>
                                            <GoodPrice
                                                orderyprice={this.state.orderyprice}
                                                postmoney={this.state.postmoney}
                                                cxuserIntergral={this.state.cxuserIntergral}
                                                balance={this.state.balance}
                                                MarketingPrice={this.state.MarketingPrice}
                                                dbje={this.state.dbje}
                                            ></GoodPrice>
                                        </View>
                                    </View>
                                </View>
                                <View className='weui-cells weui-cells-none'>
                                    <View class="weui-cell weui-cell_input">
                                        <View class="weui-cell__hd">
                                            <View class="weui-label">给掌柜留言</View>
                                        </View>
                                        <View class="weui-cell__bd ar">
                                            <Input class="weui-input" placeholder='选填45字以内' onInput={this.onInput.bind(this, 'remark')} value={this.state.remark} />
                                        </View>
                                    </View>
                                </View>
                            </Block>
                        }
                        {/* 积分兑换 exchange*/}
                        {goodType == 'exchange' &&
                            <Block>
                                <View className='weui-cells weui-cells-none'>
                                    <PreView type='view'>
                                        <PreView label='参考价格：' value={`￥${cart[0].SALE_PRICE}`}></PreView>
                                        <PreView label='兑换数量：' value={`×${cart[0].N_NUM}`}></PreView>
                                        <PreView label='扣除积分：' value={`${cart[0].N_IG_INTEGRAL}积分`}></PreView>
                                        {/* {userInfo && cart[0].N_IG_INTEGRAL && <PreView label='消费后剩余积分：' value={`${userInfo.N_MB_INTEGRAL - cart[0].N_IG_INTEGRAL}分`}></PreView>} */}
                                    </PreView>
                                </View>
                            </Block>
                        }
                        <View className='footer'>
                            <Footer goodType={goodType} orderIntegral={orderIntegral} postmoney={postmoney} orderprice={this.state.orderprice} onFootBtn={this.footBtn.bind(this)}></Footer>
                        </View>
                    </Block>
                }

            </View>
        )
    }
}

